﻿using LitJson;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.SceneManagement;
using Random = UnityEngine.Random;

class Commander
{
    static Commander m_Instance = null;
    public static Commander Instance { 
        get {
            if (m_Instance == null)
                m_Instance = new Commander();
            return m_Instance;
        }
    }
    public int m_ID;
    public string m_Name = "Human";
    public int m_Member = 0;
    public Character[] m_Characters = new Character[(int)Driver.DriveLevel.LEVEL_NULL];
    public Dictionary<string, int> m_Stocks = new Dictionary<string, int>();

    string ConfigPath = "./Commander.sav";


    Commander()
    {
#if UNITY_ANDROID
        ConfigPath = Application.persistentDataPath + "/Commander.sav";
#endif
        m_ID = Random.Range(100000, 999999);
        Init();
    }

    void Init()
    {
        load();
        SceneManager.sceneUnloaded += OnSceneUnloaded;
    }

    public void InitShip(Ship ship)
    {
        if (ship == null)
            return;
        foreach(var character in m_Characters)
        {
            if (character != null)
                character.InitShip(ship);
        }
    }
    public void Miao()
    {
        //  就是在构造的时候初始化一下
    }

    public int GetStockNumber(string key)
    {
        if (m_Stocks.ContainsKey(key))
        {
            return m_Stocks[key];
        }
        return 0;
    }
    public int AddStockNumber(string key, int number)
    {
        if (!m_Stocks.ContainsKey(key))
        {
            m_Stocks.Add(key, 0);
        }
        m_Stocks[key] += number;
        return 0;
    }


    public void save()
    {
        JsonData root = new JsonData();
        root["ID"] = m_ID;
        root["Name"] = m_Name;
        root["Member"] = m_Member;
        /// Global
        JsonData jsonCharacters = new JsonData();
        root["Character"] = jsonCharacters;
        jsonCharacters.SetJsonType(JsonType.Array);

        foreach(var c in m_Characters)
        {
            if(c == null)
            {
                jsonCharacters.Add(Character.ReturnNullJson());
            }
            else
            {
                jsonCharacters.Add(c.Save());
            }
        }

        /// Global
        JsonData jsonStocks = new JsonData();
        root["Stocks"] = jsonStocks;
        jsonStocks.SetJsonType(JsonType.Object);

        foreach(var s in m_Stocks)
        {

            jsonStocks[s.Key] = s.Value;
        }

        string data = root.ToJson();
        using (FileStream fs = new FileStream(ConfigPath, FileMode.Create, FileAccess.Write))
        {
            byte[] array = System.Text.Encoding.UTF8.GetBytes(data);
            fs.Write(array, 0, (int)array.Length);
            fs.Close();
        }
    }

    public void load()
    {
        string data;
        if (!File.Exists(ConfigPath))
        {
            return;
        }

        using (FileStream fs = new FileStream(ConfigPath, FileMode.Open, FileAccess.Read))
        {
            FileInfo info = new System.IO.FileInfo(ConfigPath);
            byte[] array = new byte[info.Length];
            fs.Read(array, 0, (int)info.Length);
            fs.Close();
            data = System.Text.Encoding.Default.GetString(array);
        }
        if (data.Length == 0)
            return;
        JsonData jsonData = JsonMapper.ToObject(data);
        load(jsonData);
    }

    public void load(JsonData json)
    {
        IDictionary<string, JsonData> jsond = json.ValueAsObject();
        if (jsond.ContainsKey("ID"))
            m_ID = jsond["ID"].ValueAsInt();
        if (jsond.ContainsKey("Name"))
            m_Name = jsond["Name"].ValueAsString();
        if (jsond.ContainsKey("Member"))
            m_Member = jsond["Member"].ValueAsInt();

        if (jsond.ContainsKey("Character"))
        {
            var characterList = jsond["Character"].ValueAsArray();
            for (int i = 0; i < characterList.Count && i< m_Characters.Length; ++i)
            {
                if (characterList[i].Count == 0)
                    m_Characters[i] = null;
                else
                    m_Characters[i] = Character.LoadS(characterList[i]);
            }
        }
        if (jsond.ContainsKey("Stocks"))
        {
            var stocksList = jsond["Stocks"].ValueAsObject();
            foreach(var stock in stocksList)
            {
                m_Stocks.Add(stock.Key, stock.Value.ValueAsInt());
            }
        }
    }

    void OnSceneUnloaded(Scene scene)
    {
        save();
    }
}